package com.iMusic.integrationLayer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.iMusic.util.Parameters;

public class DBConnection {

	Connection conn = null;
	
	/*
	 * Constructor
	 */
	DBConnection() {
		
	}
	
	/*
	 * Connects to the database
	 */
	public boolean connect() {
	
		boolean ret = false;
		
		try {
			Class.forName(Parameters.DB_DRIVER).newInstance();
			conn = DriverManager.getConnection(Parameters.DB_URL+Parameters.DB_INSTANCE,Parameters.DB_USER,Parameters.DB_PASSWD);
			ret = true;
			System.err.println("Connected to the database");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
	/*
	 * Disconnects from database
	 */
	public boolean disconnect() {
		
		boolean ret = false;
		
		try {
			conn.close();
			ret = true;
			System.err.println("Disconnected from database");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return ret;
	}

	/*
	 * Queries the Database
	 */
	public ResultSet query(String query) {
		ResultSet rs = null;

		java.sql.Statement stmt;

		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return rs;
	}
	
	/*
	 * Executes SQL statement
	 */
	public boolean execSQL(String sqlStatement) {
		boolean ret = false;

		java.sql.Statement stmt;

		try {
			stmt = conn.createStatement();
			stmt.execute(sqlStatement);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
}
